
Zepto(function($) {
    var location_ids = JSON.parse($('#hidden_location_ids').val()),
        history_qunats = {};

    location_ids.forEach(function(location) {location.max_items = 0});

    $("input[type='search']").keydown(function(e) {
        if (e.keyCode === 13 && stock_vm.search_word) {
            stock_vm.do_search();
        }
    });

    function addItems(multiple) {
        multiple = multiple || 1;
        if (!stock_vm.current_location.max_items || stock_vm.current_items < stock_vm.current_location.max_items) {
            $.ajax({
                url: '/weixin/product_stock/get_items',
                data: {
                    'search_word': stock_vm.search_word,
                    'current_items': stock_vm.current_items,
                    'numbers': multiple * stock_vm.items_per_page,
                    'orderby': stock_vm.sort_name,
                    'direction': stock_vm.sort_direction,
                    'location_id': stock_vm.current_location.id,
                    'get_max_items': stock_vm.current_location.max_items === 0,
                },
                type: 'get',
                success: function(e) {
                    var response = JSON.parse(e);
                    stock_vm.quants = stock_vm.quants.concat(response.res);
                    // stock_vm.current_items = response.current_items;

                    if (response.max_items) {
                        stock_vm.current_location.max_items = response.max_items;
                    };

                    stock_vm.do_search(stock_vm.search_type);
                },
                async: true,
            });
        };
    };


    function refresh_sort() {
        // @正翔 pg中文排序和前端排序返回的结果不同，暂时不对中文进行排序
        if (stock_vm.sort_name != 'product_name' && stock_vm.current_items >= stock_vm.current_location.max_items) {
            stock_vm.quants.sort(function(left, right) {
              var res = left[stock_vm.sort_name] >= right[stock_vm.sort_name]
              res = stock_vm.sort_direction === 'down'? res : !res;

              return res? 1 : -1;
            });
        } else {
            // stock_vm.current_items = 0;
            stock_vm.quants = [];
            addItems(stock_vm.current_page);
        };
    };

    var stock_vm = avalon.define({
        $id: 'product-stock',
        quants: [],
        search_word: '',
        sort_name: 'product_name',
        sort_direction: 'up',

        location_choose: false,  // 库位选择框

        current_location: location_ids[0],
        location_ids: location_ids,

        current_index: 0,  // 当前页（搜索条件后）
        current_length: 0,  // 全部数据（搜索条件后）

        current_page: 1,  // 当前列表分页
        items_per_page: 15,  // 每页展示多少行数据

        // current_items: 0,  // 实际数据
        $computed: {
            pages: {
                get: function() {
                    return Math.ceil(this.current_length / this.items_per_page);
                }
            },
            current_items: {
                get: function() {
                    return this.quants.length;
                }
            }
        },

        reinit: function() {
            stock_vm.current_index = 0;
            stock_vm.current_length = 0;
            stock_vm.current_page = 1;
            // stock_vm.current_items = 0;
        },

        choose_location: function(location) {
            var old_quants = [];
            stock_vm.quants.forEach(function(quant) {
                old_quants.push({
                    product_id: quant.product_id,
                    default_code: quant.default_code,
                    product_name: quant.product_name,
                    product_uom: quant.product_uom,
                    product_uom_translation: quant.product_uom_translation,
                    product_qty: quant.product_qty,
                    outgoing_qty: quant.outgoing_qty,
                    incoming_qty: quant.incoming_qty,
                    visible: quant.visible,
                })
            });

            delete history_qunats[stock_vm.current_location.id]
            history_qunats[stock_vm.current_location.id] = old_quants;
            stock_vm.quants = [];

            stock_vm.current_location = location; 
            stock_vm.reinit();

            if (history_qunats[stock_vm.current_location.id] !== undefined) {
                stock_vm.quants = history_qunats[stock_vm.current_location.id];
                stock_vm.do_search();
            } else {
                addItems();
            }

            stock_vm.toggle_location_choose();
        },

        toggle_location_choose: function() {
            stock_vm.location_choose = !stock_vm.location_choose;
            var choose = $('#list-location-choose');
            if (stock_vm.location_choose) {
                choose.addClass('show-choose');
            } else {
                choose.removeClass('show-choose');
            }
        },

        sort: function(word) {
            if (word === stock_vm.sort_name) {
                stock_vm.sort_direction = stock_vm.sort_direction === 'up'? 'down' : 'up';
            } else {
                stock_vm.sort_direction = 'up';
            }

            stock_vm.sort_name = word;
            refresh_sort();
            stock_vm.do_search();
        },
        do_search: function() {  // 暂时只支持简单的名称搜索
            stock_vm.current_index = (stock_vm.current_page - 1) * stock_vm.items_per_page;

            var word = stock_vm.search_word.toLowerCase(),
                current_page_index = 0;
                first_index = stock_vm.items_per_page * (stock_vm.current_page - 1),
                last_index = stock_vm.items_per_page * stock_vm.current_page,

            stock_vm.quants.forEach(function(quant) {
                if (current_page_index < last_index && current_page_index >= first_index) {
                    var matching = false;
                    if (word) {
                        if (quant.product_name.toLowerCase().indexOf(word) != -1 || quant.default_code.toLowerCase().indexOf(word) != -1) matching = true;
                    } else matching = true;

                    if (matching) current_page_index += 1;
                    quant.visible = matching;
                } else {
                    current_page_index += 1;
                    quant.visible = false;
                }
            });

            $.ajax({
                url: '/weixin/product_stock/get_current_length',
                data: {
                    'location_id': stock_vm.current_location.id,
                    'search_word': stock_vm.search_word,
                },
                success: function(e) {
                    var response = JSON.parse(e);
                    stock_vm.current_length = response.current_length;

                    if (stock_vm.pages && stock_vm.current_page > stock_vm.pages) {
                        stock_vm.current_page = stock_vm.pages;
                        stock_vm.do_search();
                    };
                },
                async: true,
            });

            if (current_page_index < last_index) addItems();
        },
        next_page: function() {
            if (stock_vm.current_length - stock_vm.current_index > stock_vm.items_per_page) {
                $('.content').scrollTop(0);
                stock_vm.current_page = stock_vm.current_page + 1;
                stock_vm.do_search();
            };
        },
        previous_page: function() {
            if (stock_vm.current_page > 1) {
                $('.content').scrollTop(0);
                stock_vm.current_page = stock_vm.current_page - 1;
                stock_vm.do_search();
            };
        },
    });

    stock_vm.$watch('search_word', function(word) {
        if (!word) stock_vm.do_search();
    });

    addItems();
    avalon.scan();
});
